import React, { useState } from 'react';
import { Calendar, Badge, Modal, Form, Input, Select, Button, Typography, Divider, Table, Tag, Space, DatePicker } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, CalendarOutlined } from '@ant-design/icons';
import type { Moment } from 'moment';
import moment from 'moment';
import axios from 'axios';

const { Title } = Typography;
const { Option } = Select;
const { TextArea } = Input;

interface ScheduleItem {
  id: string;
  title: string;
  platform: string;
  content: string;
  date: string;
  time: string;
  status: 'pending' | 'published' | 'failed';
}

const SchedulePlanner: React.FC = () => {
  const [scheduleItems, setScheduleItems] = useState<ScheduleItem[]>([
    {
      id: '1',
      title: '新品发布文案',
      platform: 'weibo',
      content: '我们的新产品正式发布啦！限时优惠，先到先得！',
      date: '2023-03-15',
      time: '12:00',
      status: 'pending'
    },
    {
      id: '2',
      title: '节日促销活动',
      platform: 'xiaohongshu',
      content: '五一假期特别优惠，全场商品8折起！',
      date: '2023-05-01',
      time: '09:00',
      status: 'pending'
    }
  ]);
  
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [currentItem, setCurrentItem] = useState<ScheduleItem | null>(null);
  const [form] = Form.useForm();
  
  const platforms = {
    weibo: '微博',
    xiaohongshu: '小红书',
    wechat: '微信公众号',
    douyin: '抖音'
  };
  
  const statusColors = {
    pending: 'blue',
    published: 'green',
    failed: 'red'
  };
  
  const showModal = (item?: ScheduleItem) => {
    if (item) {
      setCurrentItem(item);
      form.setFieldsValue(item);
    } else {
      setCurrentItem(null);
      form.resetFields();
    }
    setIsModalVisible(true);
  };
  
  const handleCancel = () => {
    setIsModalVisible(false);
  };
  
  const handleSubmit = async (values: any) => {
    try {
      if (currentItem) {
        // 更新已有计划
        const updatedItems = scheduleItems.map(item => 
          item.id === currentItem.id ? { ...item, ...values } : item
        );
        setScheduleItems(updatedItems);
        // await axios.put(`/api/schedules/${currentItem.id}`, values);
      } else {
        // 添加新计划
        const newItem: ScheduleItem = {
          id: Date.now().toString(),
          ...values,
          status: 'pending'
        };
        setScheduleItems([...scheduleItems, newItem]);
        // await axios.post('/api/schedules', newItem);
      }
      setIsModalVisible(false);
    } catch (error) {
      console.error('Failed to save schedule:', error);
    }
  };
  
  const handleDelete = async (id: string) => {
    try {
      setScheduleItems(scheduleItems.filter(item => item.id !== id));
      // await axios.delete(`/api/schedules/${id}`);
    } catch (error) {
      console.error('Failed to delete schedule:', error);
    }
  };
  
  const dateCellRender = (value: Moment) => {
    const dateString = value.format('YYYY-MM-DD');
    const listData = scheduleItems.filter(item => item.date === dateString);
    
    return (
      <ul style={{ listStyle: 'none', padding: 0, margin: 0 }}>
        {listData.map(item => (
          <li key={item.id}>
            <Badge 
              color={statusColors[item.status]} 
              text={item.title.length > 6 ? `${item.title.substring(0, 6)}...` : item.title} 
            />
          </li>
        ))}
      </ul>
    );
  };
  
  const columns = [
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
    },
    {
      title: '平台',
      dataIndex: 'platform',
      key: 'platform',
      render: (platform: keyof typeof platforms) => platforms[platform] || platform,
    },
    {
      title: '发布日期',
      dataIndex: 'date',
      key: 'date',
    },
    {
      title: '发布时间',
      dataIndex: 'time',
      key: 'time',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: keyof typeof statusColors) => (
        <Tag color={statusColors[status]}>
          {status === 'pending' ? '待发布' : status === 'published' ? '已发布' : '失败'}
        </Tag>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: ScheduleItem) => (
        <Space size="middle">
          <Button 
            type="text" 
            icon={<EditOutlined />} 
            onClick={() => showModal(record)} 
          />
          <Button 
            type="text" 
            danger 
            icon={<DeleteOutlined />} 
            onClick={() => handleDelete(record.id)} 
          />
        </Space>
      ),
    },
  ];
  
  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <Title level={2}>内容发布计划</Title>
        <Button 
          type="primary" 
          icon={<PlusOutlined />} 
          onClick={() => showModal()}
        >
          新建计划
        </Button>
      </div>
      
      <Divider />
      
      <Calendar dateCellRender={dateCellRender} />
      
      <Divider />
      
      <Title level={3}>发布列表</Title>
      <Table 
        columns={columns} 
        dataSource={scheduleItems} 
        rowKey="id"
        pagination={false}
      />
      
      <Modal
        title={currentItem ? "编辑发布计划" : "新建发布计划"}
        open={isModalVisible}
        onCancel={handleCancel}
        footer={null}
        destroyOnClose
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
        >
          <Form.Item
            name="title"
            label="标题"
            rules={[{ required: true, message: '请输入计划标题' }]}
          >
            <Input placeholder="请输入计划标题" />
          </Form.Item>
          
          <Form.Item
            name="platform"
            label="发布平台"
            rules={[{ required: true, message: '请选择发布平台' }]}
          >
            <Select placeholder="请选择发布平台">
              <Option value="weibo">微博</Option>
              <Option value="xiaohongshu">小红书</Option>
              <Option value="wechat">微信公众号</Option>
              <Option value="douyin">抖音</Option>
            </Select>
          </Form.Item>
          
          <Form.Item
            name="content"
            label="发布内容"
            rules={[{ required: true, message: '请输入发布内容' }]}
          >
            <TextArea rows={4} placeholder="请输入发布内容" />
          </Form.Item>
          
          <Form.Item
            name="date"
            label="发布日期"
            rules={[{ required: true, message: '请选择发布日期' }]}
          >
            <DatePicker style={{ width: '100%' }} />
          </Form.Item>
          
          <Form.Item
            name="time"
            label="发布时间"
            rules={[{ required: true, message: '请输入发布时间' }]}
          >
            <Input placeholder="请输入发布时间，例如：09:00" />
          </Form.Item>
          
          <Form.Item>
            <Button type="primary" htmlType="submit">
              保存
            </Button>
            <Button style={{ marginLeft: 8 }} onClick={handleCancel}>
              取消
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default SchedulePlanner; 